package com.chinasoft.cr.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chinasoft.cr.mapper.UserMapper;
import com.chinasoft.cr.pojo.PageItem;
import com.chinasoft.cr.pojo.Result;
import com.chinasoft.cr.pojo.User;
import com.chinasoft.cr.pojo.vo.PasswordVo;
import com.chinasoft.cr.service.UserService;
import com.chinasoft.cr.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;

@RestController
@CrossOrigin  // 解决 跨域问题
public class UserController {

    @Autowired
    UserService userService;
    @Autowired
    UserMapper userMapper;

//    @GetMapping("/api/user/userall")
//    public Result getUsers() {
//        List<User> allUsers = userService.getAllUsers();
//        Result result = new Result(200, "查询成功 ！", allUsers);
//        return result;
//    }

//    @GetMapping("/api/user/userall")
//    public Result getPageUsers(Integer pageNum, Integer pageSize) {
//        System.out.println(pageNum + ", " + pageSize);
////        List<User> users = userService.getPage(pageNum, pageSize);
//        PageItem<User> pi = userService.getPage2(pageNum, pageSize, new User());
//
//        Result result = new Result(200, "查询成功 ！", pi);
//        return result;
//    }

    @GetMapping("/api/user/usersearch")
    public Result getPageUserSearch(Integer pageNum, Integer pageSize, User query) {
        System.out.println(pageNum + ", " + pageSize);
        System.out.println(query);
        PageItem<User> pi = userService.getPage2(pageNum, pageSize, query);

        Result result = new Result(200, "查询成功 ！", pi);
        return result;
    }

    @DeleteMapping("/api/user/{id}")
    public Result deleteUser(@PathVariable Long id) {
        System.out.println("user id is " + id);
        Boolean flag = userService.deleteUser(id);

        if (flag == true) {
            Result result = new Result(200, "删除成功 ！", null);
            return result;
        } else {
            Result result = new Result(404, "删除失败，用户不存在 ！", null);
            return result;
        }
    }

    @PutMapping("/api/user")
    public Result updateUser(
            // 将 json数据格式转换为 pojo对象
            @RequestBody PasswordVo user) {
        System.out.println("--------------------update-------------------------");
        System.out.println("user is " + user);

        User u1 = userMapper.selectById(user.getId());
        System.out.println("u1:"+u1);
        System.out.println(u1.getPassword());
        System.out.println(user.getPassword2());
        if(!u1.getPassword().equals(user.getPassword2())) {
            return new Result(500, "密码与原本不相同", null);
        }
        User u = new User();
        u.setId(user.getId());
        u.setPassword(user.getPassword());
        Boolean flag = userService.updateUser(u);
        if (flag == true) {
        return new Result(200, "修改成功 ！", null);
        } else {
            Result result = new Result(404, "修改失败，用户不存在 ！", null);
            return result;
        }
    }

    @PutMapping("/api/user/edit")
    public Result editUserInfo(@RequestBody User user) {
        Boolean flag = userService.updateUser(user);
        if (flag == true) {
            return new Result(200, "修改成功 ！", null);
        } else {
            Result result = new Result(404, "修改失败，用户不存在 ！", null);
            return result;
        }
    }

    @PostMapping("/api/user/login")
    public Result login(
            // 将 json数据格式转换为 pojo对象
            @RequestBody User user) {
        System.out.println("--------------------login-------------------------");
        System.out.println("user is " + user);
            User userDb = userService.checkUser(user, "login");
//        Boolean flag = true;

        if (userDb != null) {
            String token = JwtUtils.createToken(userDb.getId().toString(), userDb.getUsername());
            Result result = new Result(200, "login成功 ！", token);
            return result;
        } else {
            Result result = new Result(404, "登录失败，密码或者账号错误 ！", null);
            return result;
        }
    }

    @GetMapping("/api/user/info")
    public Result getUserInfo(@RequestHeader("Authorization") String token) {
        System.out.println("-------------------info--------------");
        System.out.println(token);
        if (JwtUtils.verifyToken(token)) {
            // 令牌 ok
            //根据令牌获取用户的id
            String strUserId = JwtUtils.getAudience(token);
            Long userId = Long.parseLong(strUserId);
            User user = userService.getUser(userId);
            System.out.println(user.toString());
            user.setPassword(null);
            Result result = new Result(200, "userinfo成功 ！", user);
            return result;
        }
        Result result = new Result(500, "token is invalid", null);
        return result;
    }
        @PostMapping(value = "/api/user/register")
        public Result  register(@RequestBody User params ) {
            User userDb = userService.checkUser(params, "");
            try {
                if (userDb == null) {
                    int flag = userService.save(params);
                    if (flag != 0) {
                        Result result = new Result(200, "增加成功！", null);
                        return result;
                    } else {
                        Result result = new Result(404, "增加失败！", null);
                        return result;
                    }
                }

            } catch (Exception e) {
                Result result = new Result(500, "增加失败，系统错误：" + e.getMessage(), null);
                return result;
            }
            return new Result(500, "用户已存在！", null);
        }
    //上传图片
//    @PostMapping("/api/user/upload-photo/{userId}")
//    public Result uploadPhoto(@PathVariable Long userId, @RequestParam("file") MultipartFile file) {
//        if (file.isEmpty()) {
//            return new Result(400, "文件不能为空！", null);
//        }
//
//        try {
//            // 获取文件名
//            String fileName = file.getOriginalFilename();
//            // 设置存储路径
//            String uploadDir = "uploads/photos/";
//            File uploadPath = new File(uploadDir);
//            if (!uploadPath.exists()) {
//                uploadPath.mkdirs(); // 如果目录不存在，创建目录
//            }
//            String filePath = uploadDir + fileName;
//
//            // 保存文件到服务器
//            file.transferTo(new File(filePath));
//
//            // 更新数据库中的 photo 字段
//            User user = userService.getUser(userId);
//            if (user == null) {
//                return new Result(404, "用户不存在！", null);
//            }
//            user.setPhoto(filePath);
//            boolean flag = userService.updateUser(user);
//
//            if (flag) {
//                return new Result(200, "头像上传成功！", filePath);
//            } else {
//                return new Result(500, "头像上传失败！", null);
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//            return new Result(500, "文件上传失败：" + e.getMessage(), null);
//        }
//    }

}
